// import { Link, Stack } from 'expo-router';
import BasePicker from '@/components/BasePicker';
import { useEffect } from 'react';
import { ActivityIndicator, Alert, FlatList, Platform, Text, View } from 'react-native';
import { Button, Input } from 'react-native-elements';
import { SafeAreaView } from 'react-native-safe-area-context';
import tw from 'twrnc';

import { useBluetooth } from '@/utils/useBluetooth';
import Alipay from '@uiw/react-native-alipay';
import * as AppleAuthentication from 'expo-apple-authentication';
import { isWechatInstalled, registerApp, sendAuthRequest } from "expo-native-wechat";
const Login = () => {
  const { Linking, devices, connected, connectDevice, debugConnect } = useBluetooth();

  useEffect(() => {
    console.log(registerApp, '必要：初始化注册微信 - registerApp')
    registerApp("wx964290141ebe9b7b");
  }, []);

  const handlePickChange = (value: any) => {
    console.log(value, 'PickChange')
  }

  const handleWechatLogin = async (value: any) => {
    try {
      const res = await isWechatInstalled()
      console.log('是否安装微信：', res)
      if (!res.success) {
        Alert.alert(
          "提示",
          "请先安装微信应用",
          [
            {
              text: "取消",
              onPress: () => console.log("Cancel Pressed"),
              style: "cancel"
            },
            { text: "好的", onPress: () => console.log("OK Pressed") }
          ]
        );
        return;
      }
      const { data: { code } } = await sendAuthRequest();
      console.log('weixin:authInfo:resule-->>>', code);
    } catch (error) {
      console.log(error, '微信应用-error')
    }
  }

  const handleAliPayLogin = async (value: any) => {
     console.log(Alipay,'AlipayAlipay')
    // authInfoStr 是后台拼接好的验证参数
    const authInfoStr = 'app_name=mc&auth_type=AUTHACCOUNT&apiname=com.alipay.account.auth&biz_type=openservice&product_id=APP_FAST_LOGIN&scope=kuaijie&pid=2088421915791034&target_id=15946456110003465&app_id=2021001172656340&sign_type=RSA2&sign=keluG28qbbLwAcSDI4VmCNOGHJoF3xgpVeqXu1nCBCYo%2FlYYGe00fTfV9L4G73Sk7%2B4IwK%2BZV8IL%2F04cVtk6SR74lKAR3rYOoUdQ09ZrZFuQoUkO0vekajhp75IDQIg6PedCyY0SjFTqrHlH%2FImscBwitxrlSc9YbN7uW0gY34K8t7v8NhDoqzKJeoIz43UxF5U1DpUA1ISBVxwO7du1t6rYltsRhReayPS3hnvmwYSKQZUEgBvJ%2BT2XdyCaz%2FdGV907lYagPp1Oxkoaj%2FvW5NjNsRnid7vH944CoFj9XtBK%2FNTk2tBPTHFxYRQTEG1PkgkBohGpAWOFGGOuapH0ag%3D%3D';
    const resule = await Alipay.authInfo(authInfoStr);
    // resule => success=true&auth_code=9c11732de44f4f1790b63978b6fbOX53&result_code=200&alipay_open_id=20881001757376426161095132517425&user_id=2088003646494707
    console.log('zhifubai:authInfo:resule-->>>', resule);
  }

  const handleApplyAuth = () => {}

  return <SafeAreaView>
    <View>
      {
        Platform.OS === 'ios' &&
        <AppleAuthentication.AppleAuthenticationButton
          buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
          buttonStyle={AppleAuthentication.AppleAuthenticationButtonStyle.BLACK}
          cornerRadius={5}
          onPress={handleApplyAuth}
        />
      }
    </View>
    <View style={tw.style('p-2')}>
      <Button title={'微信授权'} onPress={handleWechatLogin}></Button>
    </View>
    <View style={tw.style('p-2')}>
      <Button title={'支付宝授权'} onPress={handleAliPayLogin}></Button>
    </View>
    <Text style={tw.style('text-md', 'text-red-500')}>Hello</Text>
    <Input
      label="手机快捷登录"
      placeholder='BASIC INPUT'
      keyboardType="numeric"
      errorStyle={{ color: 'red' }}
      errorMessage='ENTER A VALID ERROR HERE'
      leftIcon={
        <Text>123456</Text>
      }
    />

    <BasePicker
      columns={[
        { value: 1, label: 'JS' }, 
        { value: 2, label: 'TS' }, 
        { value: 3, label: 'NODEJS3' },
        { value: 4, label: 'NODEJS4' },
        { value: 5, label: 'NODEJS5' },
        { value: 6, label: 'NODEJS6' },
        { value: 7, label: 'NODEJS7' },
        { value: 8, label: 'NODEJS8' },
        { value: 9, label: 'NODEJS9' },
      ]}
      errorStyle={{ color: 'red' }}
      errorMessage='ENTER A VALID ERROR HERE'
      onChange={handlePickChange}
    />

    <View>
      {connected ? (
        <Text style={{ fontSize: 18, color: 'green' }}>
          ✅ 已连接：{connected.name || connected.id}
        </Text>
      ) : (
        <Text style={{ fontSize: 18, color: 'gray' }}>请选择设备连接</Text>
      )}
      <FlatList
        data={devices}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', marginVertical: 4 }}>
            <Text style={{ flex: 1 }}>
              {item.name || '未知设备'} ({item.id})
            </Text>
            {
              Linking ? 
                <ActivityIndicator color="#0000ff" />
                :
                <Button
                  title="连接"
                  onPress={() => connectDevice(item.id)}
                  disabled={!!connected}
                />
            }
            
          </View>
        )}
        ListEmptyComponent={<Text>暂无设备</Text>}
      />
    </View>
  </SafeAreaView>;
}

export default Login;